require('date-utils');
var models = require("../models"),
    Good = models.Good,
    Order = models.Order,
    User = models.User,
    Message = models.Message,
    Session = models.WCSession,
    UserDoctor = models.UserDoctor,
    PubChatPay = models.PubChatPay;
var util_wechat = require('../utils/wechatutil');
var settings = require('../config');
var randomstring = require("random-string");
var debug = require('debug')('wechat:buy');
var OAuth = require('wechat').OAuth;
var async = require('async');

var util_tool = require('../utils');
var PayConfig = require('../models/payconfig.js').PayConfig;
var Payment = require('wechat-pay').Payment;
var wechat_pay = new Payment();


module.exports = function (app) {

    /*成为咨询师*/
    app.post('/wcpay/becomedoctor', function (req, res) {
        var userDoctor = new UserDoctor();
/*        if (req.query.code) {
            new util_wechat().getOAuth(req.query.code, function (oauth, result) {
                if (result) {
                    var openid = result.openid;*/
        //var openid=0;
                    //根据openid查询用户
        var openid = req.body.code;

           userDoctor.findUserByOpenid(openid, function (err, userDoctors) {
               var msg = 'exist';
               var result = '不可重复注册！';
               if (err || !userDoctors) {
                   userDoctor.username = req.body.username;
                   userDoctor.mobilephone = req.body.mobilephone;
                   userDoctor.email = req.body.email;
                   userDoctor.about = req.body.about;
                   userDoctor.wcopenid = openid;
                   userDoctor.fordate = new Date();
                   //userDoctor.state = 0;

                   userDoctor.saveUser(function(err) {
                      if(err) {
                          debug('insert user fail', err);
                          console.log("-------------------------------------"+err);
                          //res.end('fail');
                          msg = 'fail';
                          result = '抱歉！注册咨询师失败，请重试！'
                      }else {
                          msg = 'success';
                          result = '恭喜！注册成功，请等待审核！';
                      }
                       res.render("bdrs", {
                           title: "成为咨询师",
                           result: result,
                           msg: msg
                       });

                   });

               } else {
                   console.log('user is exist');
                   res.render("bdrs", {
                       title: "成为咨询师",
                       result: result,
                       msg: msg
                   });
               }
           })
      /*          }
            });
        }*/
    });
    app.get('/wcpay/becomedoctor', function (req, res) {
        var userDoctor = new UserDoctor();
        if (req.query.code) {
            new util_wechat().getOAuth(req.query.code, function (oauth, result) {
                if (result) {
                    var openid = result.openid;

                    res.render('bdoctor', {
                        title: '注册成为咨询师',
                        code: openid
                    });
                }
            });
        }

    });

    app.get("/wcpay/goodslist", function (req, res) {

        var appid = req.query.state;
        var code = req.query.code;

        //# 获取授权openid
        util_wechat.getOauthOpenid(appid, code, function(err, data){
            if(err){
                sendPayError(res, err);
            }else{
                var openid = data.data.openid;

                //# 查询商品列表
                new Good().findGoods(function (err, goods) {
                    if (err) {
                        sendPayError(res, err);
                    } else {

                        //
                        new util_tool().getpayoffinfo(openid, function (err, payoff) {

                            if (err) {
                                sendPayError(res, err);
                            }else{
                                res.render("goodslist", {
                                    title: "商品列表",
                                    goods: goods,
                                    openid:openid,
                                    appid:appid,
                                    payoff_count: payoff.payoff_count
                                });
                            }

                        });
                    }
                })
            }
        })
        /*new Good().findGoods(function (err, goods) {
            if (err) {
                res.render("error", {
                    message: "出错啦",
                    error: err
                })
            } else {
                if (req.query.code) {
                    new util_wechat().getOAuth(req.query.code, function (oauth, result) {
                        if (result) {

                            new util_tool().getpayoffinfo(result.openid, function (err, payoff) {

                                if (err) {
                                    res.render("error", {
                                        message: "出错啦",
                                        error: err
                                    });
                                }else{
                                    res.render("goodslist", {
                                        title: "商品列表",
                                        goods: goods,
                                        openid: result.openid,
                                        payoff_count: payoff.payoff_count
                                    });
                                }

                            });
                        }
                    });
                }
                //res.redirect('wxpayjsapidemo.ejs')

            }
        })*/
    })

    app.get("/wcpay_test/goodslist", function (req, res) {
        new Good().findGoods(function (err, goods) {
            if (err) {
                res.render("error", {
                    message: "出错啦",
                    error: err
                })
            } else {
                //res.redirect('wxpayjsapidemo.ejs')
                res.render("wxpayjsapidemo", {
                    title: "商品列表",
                    goods: goods
                })
            }
        })
    })
    app.get("/wcpay/pay", function (req, res) {
        var goodid = req.query.goodid;
        goodid = goodid.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');
        new Good().findGoodById(goodid, function (err, good) {
            debug("the good", good);
            if (err) {
                res.render("error", {
                    message: "出错啦",
                    error: err
                })
            } else {
                //make tradeno
                var tradeno = randomstring({
                    length: 20,
                    numeric: true,
                    letters: false,
                    special: false
                });
                var new_payinfo = getpayinfo(settings.paySign, good.name, good.price, tradeno, req.ip);
                //生成订单
                var order = new Order();
                order.price = good.price;
                order.status = 0; //未支付
                order.date = (new Date().toFormat('YYYY-MM-DD HH24:MI:SS'));
                order.goodname = good.name;
                order.goodnumber = 1;
                order.tradeno = tradeno;
                order.servicecount = good.servicecount;
                order.saveOrder(order, function (err) {
                    if (err) {
                        debug("save order fail", err);
                        res.render("error", {
                            message: "出错啦",
                            error: err
                        })
                    } else {
                        var paydata = {
                            "tradeno": tradeno,
                            "payinfo": new_payinfo
                            //"payinfo": JSON.stringify(new_payinfo)
                        }
                        res.send(paydata);
                        /*res.render("pay", {
                            title: "购买商品",
                            good: good,
                            payinfo: JSON.stringify(new_payinfo),
                            tradeno: tradeno
                        });*/
                    }
                })

            }
        })
    })

    /*获取支付jsapi所需参数，整合版*/
    app.post("/wcpay/pay", function (req, res) {
        var appid = req.body.appid;
        var openid = req.body.openid;
        var goodid = req.body.goodid;
        goodid = goodid.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');
        new Good().findGoodById(goodid, function (err, good) {
            debug("the good", good);
            if (err) {
                sendPayError(res, err);
            } else {
                //make tradeno
                var tradeno = randomstring({
                    length: 20,
                    numeric: true,
                    letters: false,
                    special: false
                });

                //生成订单
                var order = new Order();
                order.price = good.price;
                order.status = 0; //未支付
                order.date = (new Date().toFormat('YYYY-MM-DD HH24:MI:SS'));
                order.goodname = good.name;
                order.goodnumber = 1;
                order.tradeno = tradeno;
                order.servicecount = good.servicecount;
                order.saveOrder(order, function (err) {
                    if (err) {
                        debug("save order fail", err);
                        sendPayError(res, err);
                    } else {
                        //生成支付接口参数用的信息
                        var option = {
                            appid:appid,
                            good:good,
                            ip:req.ip,
                            url:'http://117.78.6.144/wcpay/notification/notify',
                            tradeno:tradeno,
                            timestamp: getTimeStamp(),
                            noncestr: "5566521"
                        }
                        //查询微信商户数据
                        var param = {appid:appid};
                        PayConfig.findByAppid(param, function(err, conf){
                            if(err){
                                sendPayError(res, err);
                            }else{
                                option.payConfig = conf;
                                if(conf.version == '2'){
                                    var payData = createPayData2(option);
                                    var sendData = {
                                        tradeno:tradeno,
                                        payinfo:payData
                                    }
                                    res.send(sendData);

                                }else if(conf.version == '3'){
                                    createPayData3(option, function(err, data){
                                        if(err){
                                            sendPayError(res, err)
                                        }else{
                                            var sendData = {
                                                tradeno:tradeno,
                                                payinfo:data
                                            }
                                            res.send(sendData);
                                        }
                                    })
                                }
                            }
                        })
                    }
                })

            }
        })
    })

    app.get("/wcpay/pay_end", function (req, res) {
        var tradeno = req.query.tradeno;
        new Order().updateOrderStatusByTradeno(tradeno, function (err, numberaffected) {
            if (err || numberaffected == 0) {
                debug("update order fail", err);
                res.render("error", {
                    message: "出错啦",
                    error: err
                })
            } else {
                res.render("payend", {
                    title: "支付完成"
                });
            }
        })
    })

    /*
    * 服务记录列表--查询用户会话记录
    * */
    app.get("/getSessionsss", function(req,res) {
        //var sessionList = null;
        var messageList = new Array();
        if (req.query.code) {
            new util_wechat().getOAuth(req.query.code, function (oauth, result) {
                var openid;
                if (result) {
                    debug("get result is", result);
                    openid = result.openid;
                    if (openid) {
                        var message = new Message();
                        var session = new Session();
                        message.findSessionsBysid(openid, function(err, sessionList){//查询历史会话的sessionid
                            if(err){
                                debug("findSessionsBysid fail", err);
                            }else{
                                //sessionList = sessionList;
                                //for(var i=0;i<sessionList.length;i++){
                                sessionList.forEach(function(sid){
                                    message.findMessagesBysid(sid,false, function(err,messages){
                                        if(err){
                                            debug("findMessagesBysid fail", err);
                                        }else{

                                            //console.log(messages[0]);
                                            /*new util_wechat().getAPI(function (api){
                                             api.getUser(receive_openid,function(result){
                                             });
                                             });*/
                                            //查询咨询师openid
                                            session.findRididBySid(sid, function(err,receiveid){
                                                console.log(receiveid);
                                                //查询咨询师昵称
                                                new User().findUserByOpenid(receiveid.receive_openid, function(err,user){
                                                    if(err){
                                                        debug("findUserByOpenid fail", err);
                                                    }else{
                                                        messages[0].nickname = user.nickname;
                                                        messageList.push(messages[0]);//获取数据的第一条作为概要
                                                    }
                                                })
                                            })

                                        }
                                    });
                                });

                                //}
                                res.render('msglist',{
                                    title : '聊天记录',
                                    msgList : messageList,
                                    count : messageList.length
                                });
                            }


                        });
                    }
                } else {
                    res.render("error", {
                        message: "出错啦",
                        error: {
                            "status": 404
                        }
                    })
                }
            })
        }

    });

    app.get("/getSessions",function(req,res){
        if (req.query.code) {
            new util_wechat().getOAuth(req.query.code, function (oauth, result) {
                var openid;
                if (result) {
                    debug("get result is", result);
                    openid = result.openid;
                    res.render('msglists',{
                        title : '聊天记录',
                        openid : openid
                    });
                } else {

                    res.render("error", {
                        message: "出错啦",
                        error: {
                            "status": 404
                        }
                    })
                }
            });
        }
    });
    /*
     * 服务记录列表--查询用户会话记录
     * */
    app.get("/view/getMsgList", function(req,res) {
        //var sessionList = null;
        var messageList = new Array();
        var result = new Array();
        var openid = req.query.openid;
        var num = req.query.num;
        var snum = req.query.snum;
        if (openid) {
            var message = new Message();
            var session = new Session();
            session.findSessionsBysid(openid,num,snum, function(err, sessionList){//查询历史会话的sessionid
                if(err){
                    debug("findSessionsBysid fail", err);
                }else{
                    //sessionList = sessionList;
                    //for(var i=0;i<sessionList.length;i++){
                    /*for(var s=0;s<sessionList.length;s++){
                        if(sessionList[s].send_openid&&sessionList[s].receive_openid){
                            messageList.push(1);//代表有会话沟通，可能之前数据有问题会没有消息记录，前台如果判断记录数隐藏加载更多按钮的话，后面的数据就没法查询了
                            break;
                        }else{
                            messageList.push(0);
                            break;
                        }
                    }*/

                    var oid;
                    var count = 0;
                    var public_chat = 0;
                    async.whilst(function(){
                        return count<sessionList.length;
                    },function(callback){
                        var sid = sessionList[count];

                        message.findMessagesBysid(sid.id,false, function(err,messages){
                            if(err){
                                debug("findMessagesBysid fail", err);
                            }else if(messages.length>0){

                                //查询咨询者和被咨询者的两个openid
                                /*session.findRididBySid(sid, function(err,openids){
                                    //console.log(receiveid);
                                    if(err){
                                        res.render("error", {
                                            message: "出错啦",
                                            error: {
                                                "status": 500
                                            }
                                        });
                                    }else{*/
                                        public_chat = sid.public_chat;//获取对话记录的公开状态
                                        /*var ispub = '未公开';
                                         if(public_chat !=0){
                                         ispub = '已公开';
                                         }*/
                                        if(openid==sid.send_openid){
                                            oid = sid.receive_openid;//如果当前登录的为咨询者则查询咨询师昵称
                                        }else{
                                            oid = sid.send_openid;
                                        }
                                        if(oid){//避免没人抢单造成openids中无对方id的情况
                                            //查询对方昵称
                                            new User().findUserByOpenid(oid, function(err,user){
                                                if(err){
                                                    debug("findUserByOpenid fail", err);
                                                }else{
                                                    messages[0]._doc['publicChat']=public_chat;
                                                    messages[0]._doc['nickName'] = user.nickname;
                                                    //new Date().toFormat('YYYY-MM-DD HH24:MI:SS');
                                                    messages[0].date = new Date(((messages[0].date)*1000)).toFormat('YYYY-MM-DD HH24:MI:SS');
                                                    messageList.push(messages[0]);//获取数据的第一条作为概要
                                                    count++;
                                                    callback();
                                                }
                                            });
                                        }else{
                                            count++;
                                            callback();
                                        }

                                 /*   }
                                });*/

                            }else{
                                count++;
                                callback();
                            }
                        });
                    },function(err){
                        if(err){
                            debug("fail", err);
                        }else{
                            //console.log('sssssssssssss');
                            /*res.render('msglist',{
                                title : '聊天记录',
                                msgList : messageList.reverse(),
                                count : messageList.length,
                                openid : openid,
                                oid : oid
                            });*/
                            result.push(messageList);
                            result.push(openid);
                            result.push(oid);
                            res.json(result);
                        }

                    });
                }

            });
        }
    });


    /**
     * 查看详细聊天记录
     */
    app.get('/view/chatDetail', function (req, res){
        /*res.render('msgdetail', {
            title : '详细记录'

        });*/
        var sid = req.query.sid;
        var openid = req.query.openid;
        var oid = req.query.oid;
        var ispub = req.query.ispub;
        var flag = 0;//默认标记为咨询师
        //查询次会话id下所有聊天记录
        var message = new Message();
        var session = new Session();
        //查询咨询者和被咨询者的两个openid
        session.findRididBySid(sid, function(err,openids){
            //console.log(receiveid);
            if(err){
                res.render("error", {
                    message: "出错啦",
                    error: {
                        "status": 500
                    }
                });
            }else{
                if(openid==openids.send_openid){
                    oid = openids.receive_openid;//如果当前登录的为咨询者则查询咨询师昵称
                    flag = 1;//标记为咨询者
                }else{
                    oid = openids.send_openid;
                }
            }
        /*});*/

        message.findMessagesBysid(sid,false, function (err,messageList) {
            if(err){
                res.render("error", {
                    message: "出错啦",
                    error: {
                        "status": 500
                    }
                });
            }else{
                /*var count = 0;
                async.whilst(function(){
                    return count<messageList.length;
                },function(callback){

                });*/
                //查询当前用户的昵称
                new User().findUserByOpenid(openid, function(err,suser){
                    if(err){
                        debug("findUserByOpenid fail", err);
                    }else{
                        //查询对方昵称
                        new User().findUserByOpenid(oid, function(err,ruser) {
                            if (err) {
                                debug("findUserByOpenid fail", err);
                            } else {
                                //sname = user.nickname;
                                //new Date().toFormat('YYYY-MM-DD HH24:MI:SS');
                                var currentDate = new Date(((messageList[0].date) * 1000)).toFormat('YYYY-MM-DD');

                                for (var i = 0; i < messageList.length; i++) {
                                    //new User().findUserByOpenid(messageList[i].send_openid, function(err,user))

                                    if(messageList[i].send_openid==openids.send_openid){
                                        messageList[i].isreceive = 0;//标记为提问者id
                                    }else{
                                        messageList[i].isreceive = 1;
                                    }
                                    if (openid == messageList[i].send_openid) {//对用户openid重新赋值改为昵称，如果为当前用户openid改为当前用户昵称否则为对话者昵称
                                        messageList[i].send_openid = suser.nickname;
                                        if(suser.headimgurl==null){
                                            messageList[i]['headimgurl'] = "../images/default.gif"

                                        }else{
                                            messageList[i]['headimgurl'] = suser.headimgurl;
                                        }

                                    } else {
                                        messageList[i].send_openid = ruser.nickname;
                                        if(ruser.headimgurl==null){
                                            messageList[i]['headimgurl'] = "../images/default.gif"

                                        }else {
                                            messageList[i]['headimgurl'] = ruser.headimgurl;
                                        }

                                    }

                                    messageList[i].date = new Date(((messageList[i].date) * 1000)).toFormat('HH24:MI:SS');
                                }
                                res.render('msgdetail', {
                                    title : '详细记录',
                                    messageList : messageList,
                                    currentDate : currentDate,
                                    ispub : ispub,
                                    sid : sid,
                                    flag :flag
                                });
                            }
                        });
                    }
                });
            }
        });
    });
    });

    /**
     * 公开对话
     */
    app.get('/publicChat', function (req, res){
        var sessionid = req.query.sessionid;
        var flag = req.query.flag;
        var public_chat = req.query.public_chat;
        console.log(sessionid);
        var session = new Session();
        session.updateSessionPublicChat(sessionid,public_chat,function(err){
            if(err){
                debug("updateSessionPublicChat fail", err);
                res.end('false');
            }else{
                if(flag==1){
                    res.end('OK');
                }else{
                    //res.send('对话已公开！其它用户可查看前10条记录，如继续查看需付费。');
                    res.render('OK', {
                        title: '详细记录',
                        message: '对话已公开！'
                    });
                }
            }
        })
    });


    /**
     * 公开对话搜索页面
     */
    app.get('/view/pubchat', function (req, res){


        /*if (req.query.code) {
            new util_wechat().getOAuth(req.query.code, function (oauth, result) {
                var openid;
                if (result) {
                    debug("get result is", result);
                    openid = result.openid;
                    new User().findUserByOpenid(openid, function(err, user){
                        if(err){
                            res.render("error", {
                                message: "出错啦",
                                error: {
                                    "status": 404
                                }
                            })
                        }else{
                            res.render('pubchatsearch', {
                                title: '公开记录查看',
                                message: '对话已公开！',
                                uuid:user._id
                            });
                        }
                    });

                } else {

                    res.render("error", {
                        message: "出错啦",
                        error: {
                            "status": 404
                        }
                    })
                }
            });
        }else{
            var uuid = req.query.uuid;
            var room = req.query.room;
            console.log(uuid);
            if(room){
                res.render('pubchatSearchhtml', {
                    title: '公开记录查看',
                    message: '对话已公开！',
                    room:room,
                    openid:uuid
                });
            }
        }*/

        var uuid = req.query.uuid;
        var room = req.query.room;
        console.log(uuid);

        if(room){
            res.render('pubchatSearchhtml', {
                title: '公开记录查看',
                message: '对话已公开！',
                room:room,
                openid:uuid
            });
        }else{
            var openid = req.query.openid;
            new User().findUserByOpenid(openid, function(err, user){
                if(err){
                    res.render("error", {
                        message: "出错啦",
                        error: {
                            "status": 404
                        }
                    })
                }else{
                    var sid = req.query.sid;
                    res.render('pubchatsearch', {
                        title: '热门话题',
                        uuid:user._id,
                        sid:sid
                    });
                }
            });

        }

        /*var uuid = req.query.uuid;
        var room = req.query.room;
        console.log(uuid);*///20150309
        //var session = new Session();
        /*session.updateSessionPublicChat(sessionid,function(err){
            if(err){
                debug("updateSessionPublicChat fail", err);
                res.send('对话公开失败！');
            }else{
                //res.send('对话已公开！其它用户可查看前10条记录，如继续查看需付费。');
                res.render('OK', {
                    title: '详细记录',
                    message: '对话已公开！'
                });
            }
        })*/
        /*if(room){
            res.render('pubchatSearchhtml', {
                title: '公开记录查看',
                message: '对话已公开！',
                room:room,
                openid:uuid
            });
        }else{
            res.render('pubchatsearch', {
                title: '公开记录查看',
                message: '对话已公开！',
                uuid:uuid
            });
        }*///20150309
    });

    app.post('/view/pubChatSearch', function (req, res){

        var keywords = req.body.search;
        var init = req.body.init;
        var num = req.body.num;
        var snum = req.body.snum;
        var room = req.body.room;
        if(room){
            //搜索message表中关键字消息
            var message = new Message();
            var searchResult = new Array();
            if(init==0){
                message.findMessagesByKeywordsandRoom(keywords,room,num,snum, function(err,docs){//查询存在此关键字的所有sessionid集合
                    var count = 0;
                    async.whilst(function(){
                        return count<docs.length;
                    },function(callback){
                        message.findMessageBySidandContent(docs[count],keywords, function (err, messages) {//通过sessionid查询出此次会话的完整一句话
                            if (err) {
                                debug("findMessageBySidandContent fail", err);
                            } else {
                                /*searchResult.push(messages[0]);*/
                                searchResult.push(messages);
                                count++;
                                callback();
                            }
                        });
                    },function(err){
                        res.json(searchResult);
                    });
                });
            }else{//初始化推荐的内容
                var session = new Session();
                session.findSessionByPubChatandRoom(room,num,snum,function(err,docs){//查询已经被公开的会话的前10条
                    if(err){
                        debug("findSessionByPubChat fail", err);
                    }else{
                        var count = 0;
                        async.whilst(function () {
                            return count<docs.length;
                        },function(callback){
                            message.findMessagesBysid(docs[count]._id,true,function(err,docs){
                                if (err) {
                                    debug("findMessagesBysid fail", err);
                                } else {
                                    searchResult.push(docs[0]);
                                    count++;
                                    callback();
                                }
                            });
                        },function(err){
                            res.json(searchResult);
                        });

                    }

                });
            }
        }else{
            //搜索message表中关键字消息
            var message = new Message();
            var searchResult = new Array();
            if(init==0){
                message.findMessagesByKeywords(keywords,num,snum, function(err,docs){//查询存在此关键字的所有sessionid集合
                    var count = 0;
                    async.whilst(function(){
                        return count<docs.length;
                    },function(callback){
                        message.findMessageBySidandContent(docs[count],keywords, function (err, messages) {//通过sessionid查询出此次会话的完整一句话
                            if (err) {
                                debug("findMessageBySidandContent fail", err);
                            } else {
                                /*searchResult.push(messages[0]);*/
                                searchResult.push(messages);
                                count++;
                                callback();
                            }
                        });
                    },function(err){
                        res.json(searchResult);
                    });
                });
            }else{//初始化推荐的内容
                var session = new Session();
                session.findSessionByPubChat(num,snum,function(err,docs){//查询已经被公开的会话的前10条
                    if(err){
                        debug("findSessionByPubChat fail", err);
                    }else{
                        var count = 0;
                        async.whilst(function () {
                            return count<docs.length;
                        },function(callback){
                            message.findMessagesBysid(docs[count]._id,true,function(err,docs){
                                if (err) {
                                    debug("findMessagesBysid fail", err);
                                } else {
                                    searchResult.push(docs[0]);
                                    count++;
                                    callback();
                                }
                            });
                        },function(err){
                            res.json(searchResult);
                        });
                    }

                });
            }
        }


        //res.end(search);

    });

    /**
     * 查看公开的前十条记录
     */
    app.get("/view/pubChatDetail",function(req,res){
        var uuid = req.query.uuid;
        var sid = req.query.sid;
        var message = new Message();
        var session = new Session();
        var result = new Array();
        //查询当前用户openid
        var user = new User();
        var pubChatPay = new PubChatPay();
        user.findUserById(uuid,function(err, docs){
            var openid = docs.wcopenid;
           if(err){
               debug("findUserById fail", err);
           }else{
               async.waterfall([
                   function(callback){
                       pubChatPay.findPubChatPayByIds(openid,sid,function(err,pubChatPay){//查询当前用户是否有权限查看全部
                           callback(err,pubChatPay);
                       })
                   },
                   function(pubChatPay,callback){
                       session.findRididBySid(sid,function(err,session) {
                            callback(err,pubChatPay,session);

                       });
                   }],
                   function(err,pubChatPay,session){
                       if(err){
                           debug("findMessagesBysid fail", err);
                       }else if(session!=null&&openid==session.receive_openid||openid==session.send_openid||pubChatPay!=null){//如果此条消息记录为自己的或者付过费查询所有

                           message.findMessagesBysid(sid,false, function (err,messageList) {
                               if (err) {
                                   debug("findMessagesBysid fail", err);
                               } else {
                                   result.push(messageList);
                                   result.push(messageList[0].send_openid);
                                   result.push('all');
                                   res.json(result);
                               }
                           });
                       }else{
                           message.findMessagesBysid(sid,true, function (err,messageList) {
                               if (err) {
                                   debug("findMessagesBysid fail", err);
                               } else {
                                   //查询此公开记录付款总和
                                   var session = new Session();
                                   session.findReletCountBySid(sid,function(err,docs){
                                       console.log(messageList);
                                       /*res.render('pubChatDetail', {
                                        title : '详细记录',
                                        messageList : messageList,
                                        diff : messageList[0].send_openid,
                                        sum : docs.relet_count
                                        });*/
                                       //获取每次咨询费用
                                       var perincome = settings.perincome;
                                       //计算此记录总咨询费，用户咨询1次没有续费relet_count值为0,按百分比得到如果查看全部记录所支付的费用
                                       var sum = (docs.relet_count+1)*perincome*settings.proportion;
                                       var count = (docs.relet_count+1)*settings.proportion;
                                       result.push(messageList);
                                       result.push(messageList[0].send_openid);
                                       result.push(sum);
                                       result.push(count);
                                       res.json(result);
                                   });

                               }
                           });
                       }
                   });
                 /*  }

               });*/
           }
        });

    });
    /**
     * html版查看聊天记录
     */
    app.get("/view/Chatrecordhtml",function(req,res){
        var sid = req.query.sid;
        var thisopenid=req.query.thisopenid;
//        var message = new Message();
//        var session = new Session();
        var result = new Array();
        new Message().getChatDetail(sid,function(err,docs){
            if(err){
                debug("findReletCountBySid fail", err);
            }else {
                var count=0;
                async.whilst(function(){
                    return count<docs.length;
                },function(callback){
                    var user={};
                    var sendcontent=docs[count].sendcontent;
                    var msgtype=docs[count].msgtype;
                    var currentDate = new Date(((docs[count].date) * 1000)).toFormat('YYYY-MM-DD HH24:MI:SS');
                    var openid=docs[count].send_openid;
                    new User().findHtmlUserByOpenid(openid,function(err,doc){
                        //var da=new Date(((docs[i].date) * 1000)).toFormat('HH24:MI:SS');
                        user["nickname"]=doc.nickname;
                        user["headimgurl"]=doc.headimgurl;
                        user["openid"]=openid;
                        user["sendcontent"]=sendcontent;
                        user["date"]=currentDate;
                        user["msgtype"]=msgtype;
                        result.push(user);
                        count++;
                        callback();
                        console.log(user.nickname);
                    });
                },function(err){
                    res.render('msgdetailhtml',{thisopenid:thisopenid,messageList:result});
                });
            }
        });
    });
    /**
     * 查看十条以后的数据扣费
     */
    app.post("/wcpay/chatPay",function(req,res){
        var pubChatPay = new PubChatPay();
        var sid = req.body.sid;
        var uuid = req.body.uuid;
        var session = new Session();
        session.findReletCountBySid(sid,function(err,docs){
            if(err){
                debug("findReletCountBySid fail", err);
            }else{
                //获取每次咨询费用
                //var perincome = settings.perincome;
                var user = new User();
                var count = (docs.relet_count+1)*settings.proportion;
                var allocation = settings.allocation*count;//咨询用户的分成
                var receiveAllocation = (1-settings.allocation)*count;//咨询师分成

                pubChatPay.wcsessionid = sid;
                pubChatPay.count = count;//查看全部记录需要扣除此用户自身多少咨询次数
                pubChatPay.date = new Date().toFormat('YYYY-MM-DD HH24:MI:SS');
                pubChatPay.allocation = allocation;
                pubChatPay.receiveAllocation = receiveAllocation;
                pubChatPay.wcsessionid = sid;
                pubChatPay.status = 0;//未支付状态
                pubChatPay.send_openid = docs.send_openid;//用户的openid
                pubChatPay.receive_openid = docs.receive_openid;//咨询师openid
                user.findUserById(uuid,function(err,docs){//查询此用户咨询次数，判断够不够抵扣
                    if(err){
                        debug("findUserByOpenid fail", err);
                    }else{
                        pubChatPay.openid = docs.wcopenid;//当前付费用户openid
                        if(docs.count>=count){
                            user.updateUserCountByOpneIdBuy(docs.wcopenid, -count, function(err) {//扣除用户的可用咨询次数
                                if (err){
                                    debug("updateUserCountByOpneIdBuy fail", err);
                                }else{
                                    pubChatPay.savePubChatPay(function(err){//保存此次扣费信息，等用户结算时统计price
                                        if(err){
                                            debug("save order fail", err);
                                        }else{
                                            res.send('ok');
                                        }
                                    });
                                }
                            });
                        }else{
                            res.send('fail')
                        }
                    }
                });

            }

        });

    });

    /*
    * 购买记录
    * */
    app.get("/wcpay/orderlist", function (req, res) {
        /*if (req.query.code) {
            new util_wechat().getOAuth(req.query.code, function (oauth, result) {
                var openid;
                if (result) {
                    debug("get result is", result);
                    openid = result.openid;*/
        var openid = req.query.openid;
                    if (openid) {
                        new User().findUserByOpenid(openid, function (err, user) {
                            if (err || !user) {
                                debug("findUserByOpenid fail", err);
                            } else {
                                new Order().findOrderByOpenId(openid, function (err, orders) {
                                    if (err) {
                                        debug("findOrderByOpenId fail", err);
                                        res.render("error", {
                                            message: "出错啦",
                                            error: err
                                        })
                                    } else {
                                        res.render("orderlist", {
                                            title: "订单查询",
                                            orders: orders,
                                            count: Math.round(user.count)
                                        });
                                    }
                                })
                            }
                        })
                    /*}*/
                } else {
                    res.render("error", {
                        message: "出错啦",
                        error: {
                            "status": 404
                        }
                    })
                }
            /*})
        }*/
    })

//    app.get("/wcpay/socket", function(req, res) {
//        res.render('socket',{title:"aaa"});
//        //res.sendfile(__dirname + '/socket.ejs');
//        console.log("---------------");
//    });
}
//调用支付接口过程中出错
function sendPayError(res, err){
    res.render("error", {
        message: "出错啦",
        error: err
    })
}
function getpayinfo(key, goodname, totalfee, tradeno, ip) {
    var wechat = new util_wechat();
    var tfee = String(totalfee * 100);
    debug("the trade totalfee:" + totalfee);
    var timestamp = getTimeStamp();//String(Math.floor((new Date().getTime() / 1000))) //时间戳
    //pay info//pay info
    var payinfo = {
        "appid": "wx631f54c7933d782f",
        "appkey": "EbPSkAN5HQsCZafaBFZdvYZNftosVV3Vxmnwl6x95PlWNexAkttzqyl0fKODZtdm819xmd4m1kARXUu9EaJI59ek5tWSq7FfNYrrZitJYOy1GQq7CgptRSAaimxyJaTB",
        "timestamp": timestamp,
        "noncestr": "5566521"
    };
    // pkg
    var pkg = {
        bank_type: "WX",
        body: goodname, //商品描述
        partner: settings.wc_partner, //注册时分配的财付通商户号 partnerId
        spbill_create_ip: ip, //用户浏览器IP
        total_fee: tfee,
        fee_type: "1", //支付币种
        input_charset: "UTF-8", //传入参数字符 编码
        notify_url: "http://117.78.6.144/wcpay/notification/notify", //通知 URL
        out_trade_no: tradeno //商户订单号
    };


    //sort params
    var newpkg = wechat.sort(pkg);
    var newpkg_str = wechat.json2string(newpkg);
    debug("string1 sort : " + newpkg_str);

    //md5 the params string
    var mk5pkg_str = wechat.md5(newpkg_str + "&key=" + key).toUpperCase();
    debug("string1 md5 : " + mk5pkg_str);

    //encode the params value

    // var newpkg_encode = {};
    // _.each(newpkg, function(value, key, list) {
    //     newpkg_encode[key] = encodeURIComponent(value);
    // });

    var newpkg_encode = wechat.urlencode(newpkg);
    var newpkg_encode_str = wechat.json2string(newpkg_encode);
    debug("string1 encode : " + newpkg_encode_str);

    //add sign to package
    var package_str = newpkg_encode_str + "&sign=" + mk5pkg_str;
    debug("pay url : " + package_str);

    //update the package
    payinfo["package"] = package_str;

    //paysign string
    var newpayinfo = wechat.sort(payinfo);
    var newpayinfo_str = wechat.json2string(newpayinfo);
    debug("payinfo str:" + newpayinfo_str);

    //get the payinfo sha1
    var sha1_newpayinfo_str = wechat.sha1(newpayinfo_str);
    debug("payinfo sha1:" + sha1_newpayinfo_str);

    //add sha1 to the payinfo
    newpayinfo["signType"] = "SHA1";
    newpayinfo["paySign"] = sha1_newpayinfo_str;
    debug("add sign payinfo:", newpayinfo);


    //make the pramas to back
    newpayinfo["timeStamp"] = newpayinfo["timestamp"];
    newpayinfo["nonceStr"] = newpayinfo["noncestr"];
    newpayinfo["appId"] = newpayinfo["appid"];
    newpayinfo["appKey"] = newpayinfo["appkey"];
    delete newpayinfo["timestamp"];
    delete newpayinfo["noncestr"];
    delete newpayinfo["appid"];
    delete newpayinfo["appkey"];
    delete newpayinfo["appKey"];

    debug("lated payinfo:", newpayinfo);

    //return the result
    return newpayinfo;
}

//v2版本
function createPayData2(option){
    var fee = String(option.good.price * 100);
    var pkg = {
        bank_type: "WX",
        body: option.good.name, //商品描述
        partner: option.payConfig.partnerid, //注册时分配的财付通商户号 partnerId
        spbill_create_ip: option.ip, //用户浏览器IP
        total_fee: fee,
        fee_type: "1", //支付币种
        input_charset: "UTF-8", //传入参数字符 编码
        notify_url: option.url, //通知 URL
        out_trade_no: option.tradeno //商户订单号
    };
    //生成package签名
    var newpkg = wechat.sort(pkg);
    var newpkg_str = wechat.json2string(newpkg);
    var pkgSign = wechat.md5(newpkg_str + "&key=" + option.payConfig.partnerkey).toUpperCase();

    //生成package字符串
    var newpkg_encode = wechat.urlencode(newpkg);
    var newpkg_encode_str = wechat.json2string(newpkg_encode);
    var package_str = newpkg_encode_str + "&sign=" + pkgSign;

    //支付签名,参数名小写
    var payinfo = {
        "appid": option.payConfig.appid,
        "appkey": option.payConfig.paysignkey,
        "timestamp": option.timestamp,
        "noncestr": option.noncestr,
        package:package_str
    };
    var newpayinfo = wechat.sort(payinfo);
    var newpayinfo_str = wechat.json2string(newpayinfo);
    var paySign = wechat.sha1(newpayinfo_str);

    //生成支付参数
    var payData = {
        "appId": option.payConfig.appid,
        "timeStamp": option.timestamp,
        "nonceStr": option.noncestr,
        package:package_str,
        signType:'SHA1',
        paySign:paySign
    };

    return payData;
}
//v3版本
function createPayData3(option, callback){
    var fee = String(option.good.price * 100);
    var payData = {
        appId : option.payConfig.appid,
        partnerKey:option.payConfig.key,
        mchId:option.payConfig.mchid,
        notifyUrl:option.url,
        openid:option.openid,
        trade_type:'JSAPI',

        body:option.good.name,
        out_trade_no:option.tradeno,
        total_fee:fee,
        spbill_create_ip:option.ip
    }
    wechat_pay.getBrandWCPayRequestParams(payData, callback);
}

function getTimeStamp()
{
    var timestamp=new Date().getTime();
    var timestampstring = timestamp.toString();//一定要转换字符串
    //oldTimeStamp = timestampstring;
    return timestampstring;
}